package com.roger.springGreenwich.gateway.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by yulei on 2023/4/8.
 * https://blog.csdn.net/qq_41343166/article/details/117880683
 */
@Slf4j
public class JWTUtils {
    /**
     * 盐值
     */
    private static final String SING = "@1qaz2wsx0987654321";


    /**
     * 验签并返回DecodedJWT
     * @param token  令牌
     */
    public static DecodedJWT verify(String token){
        try {
            DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
            return jwt;
        }catch (Exception e){
            e.printStackTrace();
           return null;
        }
    }

    public static void main(String[] args) throws Exception{

        String token = "";

        //根据token解析数据，因为配置了全局异常处理中心，如果有异常会在全局异常中心处理异常
        DecodedJWT tokenInfo = JWTUtils.verify(token);
        System.out.println(tokenInfo);

        //获得用户信息
        String name = tokenInfo.getClaim("username").asString();
        Long id = tokenInfo.getClaim("id").asLong();
        String roles = tokenInfo.getClaim("roles").asString();

        System.out.println("解析后的");
        System.out.println(name);
        System.out.println(id);
        System.out.println(roles);

    }

}
